package com.magicborrow.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.beans.BaseBean;
import com.magicborrow.beans.StuffBean;
import com.magicborrow.beans.StuffResult;
import com.magicborrow.fragment.BorrowingFragment;
import com.magicborrow.fragment.StuffBorrowRulesFragment;
import com.magicborrow.fragment.StuffCommentsRecordFragment;
import com.magicborrow.fragment.StuffInfoFragment;
import com.magicborrow.huanxin.ChatActivity;
import com.magicborrow.utils.UIHelper;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.ViewPressedUtil;
import com.magicborrow.utils.VolleyTool;
import com.magicborrow.view.BannerView;
import com.magicborrow.views.LoadingDialog;
import com.magicborrow.views.ShareDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;

public class BorrowStuffDetailActivity extends BaseActivity implements View.OnClickListener {

    private TabLayout tlStuffDetail;
    private ViewPager vpBorrowStuff;
    private LinearLayout llMsg;
    private LinearLayout llShare;
    private LinearLayout llCollection;
    private ArrayList<String> titles;
    private ArrayList<Fragment> fragments;
    private RelativeLayout rlTop;
    private int height;
    private View vTop;
    private TextView tvTop;
    private StuffBean stuff;
    private LoadingDialog dialog;
    // private TextView chat;
    private boolean canEdit;
    private Button btnEdit;
    private BannerView bannerView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_borrow_stuff_detail);
        // setImmerseLayout();
        setHasTitle(false);
        stuff = (StuffBean) getIntent().getSerializableExtra("data");
        initView();
        initData();


    }

    private void initData() {
        dialog = new LoadingDialog(this);
        dialog.show();
        String url = "";
        if (UserTools.getUser(this) == null) {
            url = Constants.URL_GET_WARE + stuff.getId();
        } else {
            url = Constants.URL_GET_WARE + stuff.getId() + "?acc_token=" + UserTools.getUser(BorrowStuffDetailActivity.this).getAcc_token();
        }
        VolleyTool.get(url,
                null, new VolleyTool.HTTPListener() {
                    @Override
                    public <T> void onResponse(T t, int requestCode) {
                        dialog.dismiss();
                        StuffResult baseBean = (StuffResult) t;
                        if (baseBean.getCode() >= 0) {
                            stuff = baseBean.getData();
                            canEdit = getIntent().getBooleanExtra("canEdit", false);
                            setTop();
                            initView();
                            initListener();
                        } else {

                            showShortMsg(baseBean.getMessage());

                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error, int requestCode) {

                        if (dialog != null) {
                            dialog.dismiss();
                        }
                    }
                }, 0, StuffResult.class);


    }

    public StuffBean getStuff() {
        return stuff;
    }

    private void initView() {
        // chat = (TextView)findViewById(R.id.chat);
        btnEdit = (Button) findViewById(R.id.btn_edit);

        dialog = new LoadingDialog(this);
        vTop = findViewById(R.id.v_topbg);
        rlTop = (RelativeLayout) findViewById(R.id.rl_top);
        bannerView = (BannerView) findViewById(R.id.imv_top);
        final ViewGroup.LayoutParams params = bannerView.getLayoutParams();
        params.height = (int) (58.0 / 75.0 * UIHelper.getScreenWidth(this));
        height = params.height;
        bannerView.setLayoutParams(params);
        bannerView.setWh(58.0 / 75.0);
        ArrayList<String> imgUrls = new ArrayList<>();
        for (StuffBean.ImagesEntity imagesEntity : stuff.getImages()) {
            imgUrls.add(Constants.ADDRESS + imagesEntity.getOrigin());
        }
        bannerView.setAutoPlay(false);
        bannerView.setUrls(imgUrls);
       /* if (stuff.getImages() != null && stuff.getImages().size() != 0)
            ImageLoader.getInstance().displayImage(Constants.ADDRESS + stuff.getImages().get(0).getOrigin(), imvTop);*/
        tlStuffDetail = (TabLayout) findViewById(R.id.tl_stuff_detail);
        vpBorrowStuff = (ViewPager) findViewById(R.id.vp_borrow_stuff);
        llMsg = (LinearLayout) findViewById(R.id.ll_msg);
        llShare = (LinearLayout) findViewById(R.id.ll_share);
        llCollection = (LinearLayout) findViewById(R.id.ll_collection);
        llMsg.setOnTouchListener(ViewPressedUtil.TouchPress);
        setConllection(llCollection, !stuff.isFavor());
        if (UserTools.isLogin(this)) {
            if (stuff.getUser().getId() == UserTools.getUser(this).getId()) {
                LinearLayout ll = (LinearLayout) llShare.getParent();
                for (int i = 0; i < ll.getChildCount(); i++) {
                    View v = ll.getChildAt(i);
                    if (v != llShare) {
                        v.setVisibility(View.GONE);
                    }
                }

            }
        }
        if (canEdit) {
            ((View) llShare.getParent()).setVisibility(View.GONE);
            findViewById(R.id.ll_bottom).setVisibility(View.VISIBLE);

        } else {
            ((View) llShare.getParent()).setVisibility(View.VISIBLE);
            findViewById(R.id.ll_bottom).setVisibility(View.GONE);
        }
        if (titles == null) {
            titles = new ArrayList<>();
            titles.add("物品介绍");
            titles.add("租借规则");
            titles.add("历史评价");
        }
        if (fragments == null) {
            fragments = new ArrayList<>();
            fragments.add(new StuffInfoFragment());
            fragments.add(new StuffBorrowRulesFragment());
            fragments.add(new StuffCommentsRecordFragment());
        }

        tlStuffDetail.setTabMode(TabLayout.MODE_FIXED);
        vpBorrowStuff.setAdapter(new StuffDetailVPAdapter(getSupportFragmentManager()));
        tlStuffDetail.setupWithViewPager(vpBorrowStuff);
       /* vpBorrowStuff.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                ViewGroup.LayoutParams params1 = rlTop.getLayoutParams();
                if (position == 0) {
                    if (tvTop != null) {
                        tvTop.setAlpha(positionOffset);
                    }
                    params1.height = (int) ((height * (1 - Math.sqrt(positionOffset))) + positionOffset * UIHelper.getStatusHeight(BorrowStuffDetailActivity.this));
                    rlTop.setLayoutParams(params1);
                } else {
                    params1.height = UIHelper.getStatusHeight(BorrowStuffDetailActivity.this);
                    rlTop.setLayoutParams(params1);
                }
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });*/
    }

    private void initListener() {
        llMsg.setOnClickListener(this);
        llShare.setOnClickListener(this);
        llCollection.setOnClickListener(this);
        btnEdit.setOnClickListener(this);
        //   chat.setOnClickListener(this);

        findViewById(R.id.imb_more).setOnClickListener(this);
        findViewById(R.id.tv_want_borrow).setOnClickListener(this);
        findViewById(R.id.ll_share).setOnClickListener(this);
        findViewById(R.id.btn_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("acc_token", UserTools.getUser(BorrowStuffDetailActivity.this).getAcc_token());
                params.put("id", stuff.getId() + "");
                if (dialog == null) dialog = new LoadingDialog(BorrowStuffDetailActivity.this);
                dialog.show();
                VolleyTool.get(Constants.URL_GET_DELEATE_STUFF, params, new VolleyTool.HTTPListener() {
                    @Override
                    public <T> void onResponse(T t, int requestCode) {
                        dialog.dismiss();
                        BaseBean bb = (BaseBean) t;
                        if (bb.getCode() >= 0) {
                            finish();
                        } else {
                            showShortMsg(bb.getMessage());
                        }

                    }

                    @Override
                    public void onErrorResponse(VolleyError error, int requestCode) {
                        dialog.dismiss();
                    }
                }, 0, BaseBean.class);
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void setTop() {
        Window window = getWindow();

        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        tvTop = (TextView) findViewById(R.id.v_top);
        tvTop.setHeight(UIHelper.getStatusHeight(this));

        tvTop.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(final View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.imb_more:
                //TODO implement
                showPopupWindow(view);
                break;
            case R.id.tv_help:
                //TODO implement
                //  showPopupWindow(view);
                break;
            case R.id.btn_edit:
                //TODO implement
                intent = new Intent(this, PushStuffActivity.class);
                intent.putExtra("data", stuff);
                startActivity(intent);
                finish();
                //  showPopupWindow(view);
                break;
            case R.id.tv_complaints:
                //TODO implement
                if (!UserTools.isLogin(this, true))
                    return;
                intent = new Intent(this, ComplaintsActivity.class);
                intent.putExtra("id", "" + stuff.getId());
                intent.putExtra("type", "" + 1);
                startActivity(intent);
                break;
            case R.id.ll_msg:
                if (!UserTools.isLogin(this, true))
                    return;
                //TODO implement
                startActivity(new Intent(this, ChatActivity.class).putExtra("chatType", 1)
                        .putExtra("userId", stuff.getUser().getId() + "")
                        .putExtra("username", stuff.getUser().getNickname()).putExtra("avatarPath",
                                stuff.getUser().getAvatar80()));
                break;
            case R.id.ll_share:
                if (!UserTools.isLogin(this, true))
                    return;
                //TODO implement
                ShareDialog shreDialog = new ShareDialog(this);
                shreDialog.setData(stuff);
                shreDialog.show();
                break;
            case R.id.ll_collection:
                if (!UserTools.isLogin(this, true))
                    return;

                HashMap<String, String> params = new HashMap<>();
                params.put("id", stuff.getId() + "");
                params.put("acc_token", UserTools.getUser(this).getAcc_token() + "");
                String url = "";
                int code = 0;
                if (stuff.isFavor()) {
                    url = Constants.URL_GET_UN_CONLLECTION;
                    code = 1;
                } else {
                    url = Constants.URL_GET_CONLLECTION;
                    code = 0;
                }
                dialog.show();
                VolleyTool.get(url, params, new VolleyTool.HTTPListener() {
                    @Override
                    public <T> void onResponse(T t, int requestCode) {
                        dialog.dismiss();
                        BaseBean bean = (BaseBean) t;
                        if (bean.getCode() >= 0) {

                            setConllection((LinearLayout) view, stuff.isFavor());
                            stuff.setFavors(stuff.isFavor() ? stuff.getFavors() - 1 : stuff.getFavors() + 1);
                            stuff.setFavor(!stuff.isFavor());
                            ((StuffInfoFragment) fragments.get(0)).initdata();
                            if (BorrowingFragment.instance != null)
                                BorrowingFragment.instance.changeFavor(stuff.getId(), stuff.isFavor());

                        } else {
                            showShortMsg(bean.getMessage());
                        }

                    }

                    @Override
                    public void onErrorResponse(VolleyError error, int requestCode) {
                        dialog.dismiss();
                    }
                }, code, BaseBean.class);
                //TODO implement
                break;
            case R.id.tv_want_borrow:
                if (!UserTools.isLogin(this, true))
                    return;
                intent = getIntent();
                intent.setClass(this, BorrowingActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void setConllection(LinearLayout ll, boolean selected) {
        ImageView imv = (ImageView) ll.getChildAt(0);
        TextView tv = (TextView) ll.getChildAt(1);
        if (selected) {
            imv.setImageDrawable(getResources().getDrawable(R.mipmap.collection_nor));
            tv.setTextColor(getResources().getColor(R.color.text_color_light));
        } else {
            imv.setImageDrawable(getResources().getDrawable(R.mipmap.collection_pre));
            tv.setTextColor(getResources().getColor(R.color.title_color));
        }
        ll.setSelected(!selected);
    }

    private void showPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = getLayoutInflater().inflate(
                R.layout.more_pop, null);
        TextView tvComplaints = (TextView) contentView.findViewById(R.id.tv_complaints);
        TextView tvHelp = (TextView) contentView.findViewById(R.id.tv_help);
        tvComplaints.setOnClickListener(this);
        tvHelp.setOnClickListener(this);


        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 设置好参数之后再show
        popupWindow.showAsDropDown(view, 20, 20);

    }


    class StuffDetailVPAdapter extends FragmentPagerAdapter {
        public StuffDetailVPAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return titles.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position % titles.size());
        }
    }

}
